package com.glq1218.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.glq1218.constant.Constants;
import com.glq1218.domain.entity.Article;
import com.glq1218.domain.entity.User;
import com.glq1218.domain.vo.ArticleListVo;
import com.glq1218.domain.vo.PageVo;
import com.glq1218.mapper.ArticleMapper;
import com.glq1218.mapper.UserMapper;
import com.glq1218.response.ResponseResult;
import com.glq1218.service.ArticleService;
import com.glq1218.service.UserService;
import com.glq1218.util.BeanCopyUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * (Article)表服务实现类
 *
 * @author glq1218
 * @since 2022-10-21 23:36:50
 */
@Service("articleService")
public class ArticleServiceImpl extends ServiceImpl<ArticleMapper, Article> implements ArticleService {

    @Autowired
    private UserService userService;
    @Autowired
    private UserMapper userMapper;
    @Override
    public ResponseResult<PageVo<ArticleListVo>> listArticles(Integer pageNum, Integer pageSize) {
        LambdaQueryWrapper<Article> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Article::getStatus, Constants.SUCCESS);
        Page<Article> page = new Page<>(pageNum, pageSize);
        page(page,lambdaQueryWrapper);
        List<Article> articleList = page.getRecords();
        List<ArticleListVo> articleListVOList = BeanCopyUtils.copyBeanList(articleList, ArticleListVo.class);
        long total = page.getTotal();
        PageVo<ArticleListVo> articleVOPageVo = new PageVo<>(total, articleListVOList);

        articleListVOList = articleListVOList.stream().map(articleListVo -> {
            LambdaQueryWrapper<User> userLambdaQueryWrapper = new LambdaQueryWrapper<>();
            userLambdaQueryWrapper.select(User::getNickname).eq(User::getId, articleListVo.getId());
            User user = userMapper.selectOne(userLambdaQueryWrapper);
            articleListVo.setAuthor(user.getNickname());
            return articleListVo;
        }).collect(Collectors.toList());
        return ResponseResult.success(articleVOPageVo);
    }
}

